﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AMS.Core.Services;
using AMS.Core.Data;
using AMS.Core.Cryptography;
using AMS.DD35.WebMVP.State;

namespace AMS.DD35.WebMVP.Models
{
    public class LoginModel : ILoginModel
    {
        ILoginService _login;
        IStateManager _state;
        // note: ILoginService.SessionManager not implemented; is server side

        #region Login Observer
        public event EventHandler LoginFailed;
        protected void RaiseLoginFailed(EventArgs e)
        {
            if (LoginFailed != null)
                LoginFailed(this, e);
        }

        public event EventHandler LoginSucceeded;
        protected void RaiseLoginSucceeded(EventArgs args)
        {
            if (LoginSucceeded != null)
                LoginSucceeded(this, args);
        }

        public event EventHandler LogoutSucceeded;
        protected void RaiseLogoutSucceeded(EventArgs args)
        {
            if (LogoutSucceeded != null)
                LogoutSucceeded(this, args);
        }
        #endregion

        public LoginModel(ILoginService loginService, IStateManager stateManager)
        {
            this._login = loginService;
            this._state = stateManager;
        }

        public void Login(string userName, string password)
        {
            IHasher hasher = new Hasher();
            string pwHash = hasher.GetHash(password);
            // TODO: implement server-stored salt

            try
            {
                _state.SessionVariable = _login.AttemptLogin(new LoginData(userName, pwHash));
                _state.UserName = userName;
                RaiseLoginSucceeded(EventArgs.Empty);
            }
            catch (Exception ex)
            {
                RaiseLoginFailed(EventArgs.Empty);
            }
        }

        public void Logout()
        {
            _login.Logout(_state.SessionVariable);
            _state.SessionVariable = null;
            _state.UserName = null;
            RaiseLogoutSucceeded(EventArgs.Empty);
        }
    }
}